<!--智慧消防V1.0-admin页面-->
<template>
    <div class="bg">
        <top-header/>
        <div style="height: calc(100vh - 70px)" class="body-box">
            <div class="content-box">
                <div>
                    <div style="height: 30vh">
                        <dv-border-box-1 v-if="videoStatus">
                            <div style="padding: 30px;color: #fff">
                                <el-row :gutter="20">
                                    <el-col :span="6" style="height: 15vh;text-align: center">
                                        <video ref="localVideo" width="100%" height="100%" playsinline autoplay></video>
                                    </el-col>
                                    <el-col :span="6" style="height: 15vh;text-align: center" >
                                        <video ref="remoteVideo0" width="100%" height="100%" playsinline autoplay></video>
                                    </el-col>
                                    <el-col :span="6" style="height: 15vh;text-align: center" >
                                        <video ref="remoteVideo1" width="100%" height="100%" playsinline autoplay></video>
                                    </el-col>
                                    <el-col :span="6" style="height: 15vh;text-align: center" >
                                        <video ref="remoteVideo2" width="100%" height="100%" playsinline autoplay></video>
                                    </el-col>
                                    <el-col :span="6" style="height: 15vh;text-align: center" >
                                        <video ref="remoteVideo3" width="100%" height="100%" playsinline autoplay></video>
                                    </el-col>
                                    <el-col :span="6" style="height: 15vh;text-align: center" >
                                        <video ref="remoteVideo4" width="100%" height="100%" playsinline autoplay></video>
                                    </el-col>
                                    <el-col :span="6" style="height: 15vh;text-align: center" >
                                        <video ref="remoteVideo5" width="100%" height="100%" playsinline autoplay></video>
                                    </el-col>
                                    <el-col :span="6" style="height: 15vh;text-align: center">
<!--                                        <div>-->
<!--                                            <el-button @click="call" size="mini" type="warning">拉人</el-button>-->
<!--                                        </div>-->
                                        <div>
                                            <el-button style="margin-top: 10px" @click="generateFire" size="mini" type="danger">
                                                火情
                                            </el-button>
                                        </div>
                                        <div>
                                            <el-button @click="leaveVideo" size="mini" type="warning">挂断</el-button>
                                        </div>
                                    </el-col>
<!--                                    <el-col :span="20" style="height: 15vh;text-align: center">-->
<!--                                        <el-form :model="userFrom" ref="userFrom"  label-width="80px" :hidden="hidden">-->
<!--                                            <el-form-item label="拉取用户" prop="userId">-->
<!--                                                <el-select v-model="userFrom.userId" placeholder="请选择用户"-->
<!--                                                           @change="userChange(userFrom.userId)" style="width: 100%">-->
<!--                                                    <el-option v-for="(item,index) in userList" :key="index"  :value="item.ucId" :label="item.name" ></el-option>-->
<!--                                                </el-select>-->
<!--                                            </el-form-item>-->
<!--                                        </el-form>-->
<!--                                    </el-col>-->
                                </el-row>
                            </div>
                        </dv-border-box-1>
                        <dv-border-box-1 v-else>
                            <div style="padding: 30px;color: #fff">
                                任务完成度
                                <el-table
                                        :data="enterList"
                                        style="width: 100%;height: 170px;overflow:auto">
                                    <el-table-column
                                            prop="enterpriseName"
                                            label="企业名称">
                                    </el-table-column>
                                    <el-table-column
                                            prop="mobile"
                                            label="电话">
                                    </el-table-column>
                                    <el-table-column
                                            prop="address"
                                            label="任务领取">
                                        <template slot-scope="slot">
                                            <el-progress :percentage="Math.floor(slot.row.receiveTaskSize*100/slot.row.dailyTaskSize)"></el-progress>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </div>
                        </dv-border-box-1>
                    </div>
                                        <div style="height: 30vh">
                                            <dv-border-box-1>
                                                <div style="padding: 30px;color: #fff">
                                                    设备数据展示
                                                    <div style="line-height: 60px;text-align: center">
                                                        <dv-active-ring-chart :config="config"  style="height: 240px;width: 240px"  />
                    <!--                                    //设备总数：{{deviceTotal}}个-->
                                                    </div>
                                                </div>
                                            </dv-border-box-1>
                                        </div>
                                        <div style="height: 30vh">
                                            <dv-border-box-1>
                                                <div style="padding: 30px;color: #fff">
                                                    异常情况展示
                                                    <el-table
                                                            :data="enterList"
                                                            style="width: 100%;height: 170px;overflow:auto">
                                                        <el-table-column
                                                                prop="enterpriseName"
                                                                label="企业名称">
                                                        </el-table-column>
                                                        <el-table-column
                                                                prop="mobile"
                                                                label="电话">
                                                        </el-table-column>
                                                        <el-table-column
                                                                prop="address"
                                                                label="异常情况">
                                                            <template slot-scope="slot">
                                                                <el-progress :percentage="Math.floor(slot.row.feedNonEneSize*100/slot.row.nonEmeSize)"></el-progress>
                                                            </template>
                                                        </el-table-column>
                                                    </el-table>
                                                </div>
                                            </dv-border-box-1>
                                        </div>
                </div>
                <div>
                    <dv-border-box-13>
                        <div style="padding: 30px;width: 100%;height: calc( 100vh - 80px)">
                            <baidu-map class="bm-view"  :zoom="13" @ready="initMap" center="哈密市"
                                       :scroll-wheel-zoom="true">
                                <bm-map-type :map-types="['BMAP_NORMAL_MAP', 'BMAP_SATELLITE_MAP']" anchor="BMAP_ANCHOR_TOP_LEFT"></bm-map-type>
                                <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
                                <bm-control anchor="BMAP_ANCHOR_TOP_LEFT" :offset="{width: 100, height: 10}">
                                    <div>
                                        展示类型：
                                        <el-select v-model="value" size="mini" style="width: 100px" @change="getPoints">
                                            <el-option
                                                    v-for="item in options"
                                                    :key="item.value"
                                                    :label="item.label"
                                                    :value="item.value">
                                            </el-option>
                                        </el-select>
                                    </div>
                                </bm-control>
                                <bml-marker-clusterer :averageCenter="true">
                                    <bm-marker v-for="(item,index) in fireCompanyList" :key="index"
                                               :position="{lng:item.longitude,lat:item.latitude}"
                                               @click="clickMarker(item)"
                                               :icon="{url:getMarkIcon(item.type), size: {width: 100, height:100}}">
                                    </bm-marker>
                                    <bm-info-window
                                            :show="show"
                                            :position="position"
                                            @close="infoWindowClose"
                                            @open="infoWindowOpen">
                                        名称：{{fireCompanyInfo.name}}<br>
                                        类型：{{fireCompanyInfo.name}}<br>
                                        负责人：{{fireCompanyInfo.person}}<br>
                                        联系电话：{{fireCompanyInfo.tel}}<br>
                                        类型：{{fireCompanyInfo.type}}<br>
                                        详细地址：{{fireCompanyInfo.address}}<br>
                                    </bm-info-window>
                                </bml-marker-clusterer>
                            </baidu-map>
                        </div>
                    </dv-border-box-13>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import 'aliyun-webrtc-sdk'
import {BmlMarkerClusterer} from 'vue-baidu-map'
import TopHeader from "@/views/bigScreen/topHeader.vue";
import {getInFireTypeMapFlagList} from "@/api/fireTypeMap";
import {joinChannel, pullPerson} from "@/api/alirtc";
import {getDeviceTotal, getNonEmergencyPage} from "@/api/common";
import {generateFire,getInUserList} from "@/api/enterprise";
export default {
    name: 'DashboardAdmin',
    components: {TopHeader,BmlMarkerClusterer},
    data() {
        return {
            BMap:[],
            fireCompanyList:{},
            fireCompanyInfo:[],
            position:{},
            content:'',
            show:false,
            videoStatus:false,
            remoteList:[],
            options: [
                {
                    value: 0,
                    label: '全部'
                }, {
                    value: 1,
                    label: '消防队'
                },
                {
                    value: 2,
                    label: '消防站'
                }, {
                    value: 3,
                    label: '警务站'
                }, {
                    value: 4,
                    label: '企业'
                }, {
                    value: 5,
                    label: '设备'
                }, {
                    value: 6,
                    label: '重点场所'
                }],
            value: 0,
            webSock:null,
            aliWebrtc:{},
            deviceTotal:0,
            enterList:[],
            config:{
                data:[
                    {
                        name: '液位水表',
                        value: 1
                    },
                    {
                        name: '压力水表',
                        value: 1
                    },
                    {
                        name: '感烟探测器',
                        value: 4
                    }
                ],
                digitalFlopStyle: {
                    fontSize: 25,
                    fill: '#fff'
                },
                rowGap:-1,
                lineWidth: 10
            },
            hidden:true,
            userFrom:{},
            userList:[],
            userId:"",
            beforeUnloadTime: '',
            gapTime: ''

        }
    },
    created() {
        this.getInFireTypeMapFlagList(0)
        this.initWebSocket()
        this.$nextTick(() => {
            this.initAliRtc()
        });
        getDeviceTotal({}).then(res=>{
            this.deviceTotal = res.data
        })
        getNonEmergencyPage({}).then(res=>{
            this.enterList = res.data.list
        })
    },
    methods: {
        initAliRtc(){
            this.aliWebrtc = new AliRtcEngine();
            this.isSupport(this.aliWebrtc,true)
        },
        //校验当前设备是否支持
        isSupport(val,debug){
            let option = {}
            if (debug){
                option.isDebug=true
            }
            val.isSupport(option).then((res)=>{
                this.onJoinEvent(val)
                this.onPublisher(val)
                this.onBye(val)
                this.onLeave(val)
                this.OnRefresh(val)
                //this.startPreview(val)
            }).catch((error)=>{
                console.log("不支持webrtc",error.message)
            })
        },
        //本地预览
        startPreview(val){
            this.aliWebrtc.startPreview(this.$refs.localVideo).then(()=>{
                console.log("本地预览")
            }).catch((error) => {
                console.log("预览失败",error)
            });
        },
        //推发布流
        publish(val){
            val.configLocalAudioPublish = true;
            val.configLocalCameraPublish = true;
            val.publish().then(()=>{
                console.log("发布流成功")
            } ,(error)=>{
                console.log("发布流失败",error);
            });
        },
        // remote用户加入房间 onJoin
        onJoinEvent(val){
            val.on("onJoin", (publisher) => {
                console.log(publisher)
                if(publisher.userId){
                    console.log(publisher.userId)
                }
                //重置订阅状态
                //默认订阅远端音频和视频大流，但需要调用subscribe才能生效
                //这里取消默认订阅，根据需求进行订阅
                val.configRemoteAudio(publisher.userId, true);
                val.configRemoteCameraTrack(publisher.userId, true, true);
                // showAlert(publisher.displayName + "加入房间","success");
                console.log(publisher.displayName + "加入房间");
            });
        },
        //remote流发布事件 onPublish
        onPublisher(val){
            val.on("onPublisher", (publisher) => {
                val.subscribe(publisher.userId).then((userId)=>{
                    this.$nextTick(() => {
                        val.setDisplayRemoteVideo(userId,this.$refs["remoteVideo"+(this.remoteList.length-1)],1)
                    });
                },(error)=>{
                    console.log(error.message);
                });
                let index = this.remoteList.indexOf(publisher);
                console.log(index)
                if (index === -1&&this.remoteList.length<7) {
                    //新增
                    this.remoteList.push(publisher)
                }
            });
        },
        //remote流结束发布事件 onUnPublisher
        onUnPublisher(val){
            val.on("onUnPublisher", (publisher) => {
                console.log("onUnPublisher",publisher);
                // detelePublisher(publisher.userId);
                // removeDom(publisher.userId);
                // initialization(publisher.userId);
            });
        },
        // 被服务器踢出或者频道关闭时回调 onBye
        onBye(val){
            val.on("onBye",(message) =>{
                //1:被服务器踢出
                //2:频道关闭
                //3:同一个ID在其他端登录,被服务器踢出
                var msg;
                switch (message.code) {
                    case 1:
                        msg = "被服务器踢出";
                        break;
                    case 2:
                        msg = "频道关闭";
                        break;
                    case 3:
                        msg = "同一个ID在其他端登录,被服务器踢出";
                        break;
                    default:
                        msg = "onBye";
                }

            });
        },
        leaveVideo(){
            this.aliWebrtc.leaveChannel();
            this.aliWebrtc.dispose();
            this.videoStatus = false
        },
        generateFire(){
            generateFire({ucId:this.userId}).then(res => {

            }).catch(res => {
                console.log()
            })
        },
        // call(){
        //     this.hidden=false
        // },
        // getInUserList(){
        //     getInUserList({deleted:false}).then(res=>{
        //         console.log(res.data)
        //         this.userList = res.data
        //     }).catch(error=>{
        //         alert("获取用户列表失败")
        //     })
        // },
        // userChange(val){
        //     console.log(val)
        //     console.log(this.userId)
        //     pullPerson({userId:this.userId,channelId:val}).then(res=>{
        //
        //     }).catch(error=>{
        //
        //     })
        // },
        /**
         * 检测到用户离开频道
         * 更新用户列表
         * 移除用户视图
         */
        onLeave(val){
            val.on("onLeave", (publisher) => {
                console.log(publisher);
                let index = this.remoteList.findIndex(function(item) {
                    return item.userId === publisher.userId;
                });
                console.log(index)
                this.remoteList.splice(index,1)
                if (this.remoteList.length<1){
                    this.leaveVideo()
                }
            })
        },
        //页面刷新时调用
        OnRefresh(val){
            window.onbeforeunload=function (e) {
                if (!val){
                    console.log("isSupport失败");
                    return ;
                }
                val.leaveChannel();
                val.dispose();
            }
        },
        //移除 dom
        endVideo(val){
            if (val!=null){
                val.leaveChannel();
                val.dispose();
            }
        },
        getMarkIcon(val){
            let icon = "http://developer.baidu.com/map/jsdemo/img/fox.gif";
            switch (val) {
                case 1:
                    icon = 'https://ifire-test.oss-cn-beijing.aliyuncs.com/logo/admin/ADMIN123456524/2021/03/048ac46d-9a2d-4f04-a85c-86dee67fc76e.png'
                    break;
                case 2:
                    icon = 'https://ifire-test.oss-cn-beijing.aliyuncs.com/logo/admin/ADMIN123456524/2021/03/35861261-5199-42d9-a700-bca5903fc355.png'
                    break;
                case 3:
                    icon = 'https://ifire-test.oss-cn-beijing.aliyuncs.com/logo/admin/ADMIN123456524/2021/03/33422882-e03f-4f29-bc02-11dc9d46725a.png'
                    break;
                case 4:
                    icon = 'https://ifire-test.oss-cn-beijing.aliyuncs.com/logo/admin/ADMIN123456524/2021/03/fd36de6b-ea86-42e0-858f-b5c5f23cc4ee.png'
                    break;
                case 5:
                    icon = 'https://ifire-test.oss-cn-beijing.aliyuncs.com/logo/admin/ADMIN123456524/2021/03/a8cf50d3-4cf8-468d-8fef-4d72c08c7a50.png'
                    break;
                case 6:
                    icon = 'https://ifire-test.oss-cn-beijing.aliyuncs.com/logo/admin/ADMIN123456524/2021/03/17b466b7-f191-4c9e-9277-ba0e6698ec51.png'
                    break;
                default:
                    break;
            }
            return icon;
        },
        initMap ({BMap,map}) {

        },
        infoWindowClose() {
            this.show = false;
        },
        infoWindowOpen() {
            this.show = true;
        },
        //获取标点信息列表
        getInFireTypeMapFlagList(val){
            getInFireTypeMapFlagList({ deleted:false,type:val}).then(res=>{
                this.fireCompanyList = res.data
            })
        },
        clickMarker (val) {
            this.position = { lng:val.longitude,lat:val.latitude };
            this.fireCompanyInfo=val;
            this.content=val.name;
            this.show = true;
        },
        //获取设备坐标点信息
        getPoints(val){
            this.getInFireTypeMapFlagList(val)
            this.show = false
        },
        // ws://192.168.20.76:9905/webSocket/
        initWebSocket(){
            const wsUri = "wss://ifire.uchung.com/wss/webSocket/"+sessionStorage.getItem('ucId');
            this.websock = new WebSocket(wsUri);
            this.websock.onmessage = this.webSocketOnmessage;
            this.websock.onopen = this.webSocketOnOpen;
            this.websock.onerror = this.websocketOnError;
            this.websock.onclose = this.webSocketClose;
        },
        webSocketOnOpen(){ //连接建立之后执行send方法发送数据
            let actions = {"type":"online","ucId":sessionStorage.getItem('ucId')};
            this.webSocketSend(JSON.stringify(actions));
        },
        websocketOnError(){//连接建立失败重连
            this.initWebSocket();
        },
        webSocketOnmessage(e){ //b
            console.log(e)
            console.log(e.data)
            let obj = JSON.parse(e.data);
            if (obj.type=='joinChannel'){
                //this.leaveVideo()
                this.joinChannel(obj)
                this.userId = obj.channel.substring(6)
            }
        },
        webSocketSend(Data){//数据发送
            console.log(Data)
            this.websock.send(Data);
        },
        webSocketClose(e){  //关闭
            console.log('断开连接',e);
        },
        //加入视频通话
        joinChannel(val){
            let _this = this;
            this.videoStatus = true;
            joinChannel({displayName:"消防队",channelId:val.channel.substring(6),admin:true}).then(res=>{
                console.log(res.data)
                _this.aliWebrtc.joinChannel(res.data,"消防队").then(obj=>{
                    _this.$nextTick(() => {
                        _this.publish(_this.aliWebrtc)
                        _this.startPreview(_this.aliWebrtc)
                    });
                    console.log("加入频道成功")
                }).catch((error)=>{
                    console.log("加入频道失败",error)
                })
            }).catch(error=>{
                console.log("加入频道失败",error)
            })
            // this.aliWebrtc.joinChannel(val,"消防队").then(obj=>{
            //     this.$nextTick(() => {
            //         _this.publish(_this.aliWebrtc)
            //         _this.startPreview(_this.aliWebrtc)
            //     });
            //     console.log("加入频道成功")
            // }).catch((error)=>{
            //     console.log("加入频道失败",error)
            // })
        },
        beforeunloadHandler(){
            this.beforeUnloadTime=new Date().getTime();
        },
        unloadHandler(e){
            this.gapTime=new Date().getTime()-this.beforeUnloadTime;
            //判断是窗口关闭还是刷新
            if(this.gapTime<=5){//浏览器关闭
                //自己的操作行为
                let  actions = {"type":"offline","ucId":sessionStorage.getItem('ucId')};
                this.webSocketSend(JSON.stringify(actions));
                this.webSock.close() //离开路由之后断开websocket连接
            }
        }
    },
    mounted () {
        window.addEventListener('beforeunload', e => this.beforeunloadHandler(e))
        window.addEventListener('unload', e => this.unloadHandler(e))
    },
    destroyed() {
        window.removeEventListener('beforeunload', e => this.beforeunloadHandler(e))
        window.removeEventListener('unload', e => this.unloadHandler(e))

    },



}
</script>

<style lang="scss" scoped>
.dashboard-editor-container {
    padding: 32px;
    background-color: rgb(240, 242, 245);
    position: relative;

    .github-corner {
        position: absolute;
        top: 0px;
        border: 0;
        right: 0;
    }

    .chart-wrapper {
        background: #fff;
        padding: 16px 16px 0;
        margin-bottom: 32px;
    }
}

@media (max-width:1024px) {
    .chart-wrapper {
        padding: 8px;
    }
}

.bm-view {
    width: 100%;
    height: calc(100vh - 138px)
}

.body-box {
    margin-top: 0.2rem;
    display: flex;
    flex-direction: column;

    //下方区域的布局
    .content-box {
        display: grid;
        grid-template-columns: 3fr 7fr;
    }
}
</style>
